package com.ias.agdis_r.manager;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.ias.agdis_r.R;
import com.ias.agdis_r.util.ClsUtils;

/**
 * 蓝牙管理类 实现检测设备是否支持蓝牙、获取蓝牙状态、打开（关闭）蓝牙、搜索附近蓝牙设备、通过设备名获取设备mac地址、配对并连接指定mac地址的设备
 * 获取本机蓝牙MAC地址、本机可以被搜索等
 * 
 * @author wanghu
 * 
 */
public class BlueToothManager {
	static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
	private static BlueToothManager instance = null;
	private BluetoothAdapter btAdapt = BluetoothAdapter.getDefaultAdapter();// 初始化本机蓝牙功能
	List<BluetoothDevice> listDevices = new ArrayList<BluetoothDevice>();// 搜索到的蓝牙列表
	public static BluetoothSocket btSocket;
	private boolean isOpen = false; // 保存蓝牙目前所处状态的事件
	private boolean isSearch = false;
	// 更新网络状态计时器
	private Timer operateBTTimer; // 开关蓝牙定时器
	// 更新网络状态任务
	private OperateBTTimerTask operateBTTimerTask;
	private Context context = DataBaseManager.getInstance().getContext();

			/**
             * 开关蓝牙定时任务
             */
	class OperateBTTimerTask extends TimerTask {
		@Override
		public void run() {
			if (btAdapt == null) {
				// 如果未获得蓝牙适配器，停止蓝牙Timer
				stopOperateBTTimer();
			}
			// 如果蓝牙设置的状态是打开
			else if (isOpen()) {
				// 如果蓝牙已经打开
				if (btAdapt.getState() == BluetoothAdapter.STATE_ON) {

					// 停止Timer任务
					stopOperateBTTimer();
				} else {
					// 打开蓝牙
					openBluetooth();
				}
			}
			// 如果蓝牙设置的状态是关闭
			else {
				if (btAdapt.getState() == BluetoothAdapter.STATE_OFF) {
					// 停止Timer任务
					stopOperateBTTimer();
				} else {
					// 关闭蓝牙
					closeBluetooth();
				}
			}
		}
	}

	public void startOperateBTTimer() {
		if (operateBTTimer == null) {

			operateBTTimer = new Timer(true);
		}
		// 停止已有的蓝牙操作任务
		stopOperateBTTimer();
		operateBTTimerTask = new OperateBTTimerTask();
		// 新建一个任务
		operateBTTimer.schedule(operateBTTimerTask, 1 * 1000);
	}

	/**
	 * 停止操作蓝牙任务任务
	 */
	public void stopOperateBTTimer() {

		if (operateBTTimer != null) {
			if (operateBTTimerTask != null) {

				operateBTTimerTask.cancel(); // 将原任务从队列中移除
				operateBTTimerTask = null;
			}
		}
	}

	/**
	 * 单例模式
	 * 
	 * @return
	 */
	public static BlueToothManager getInstance() {
		if (instance == null) {
			instance = new BlueToothManager();
		}
		return instance;
	}

	/**
	 * 检测设备是否支持蓝牙
	 * 
	 * @return
	 */
	public boolean BluetoothEnable() {
		if (btAdapt != null) {
			return true;
		}
		return false;
	}

	/**
	 * 打开蓝牙
	 */
	public void openBluetooth() {
		try {
			// 设置蓝牙应该存在的状态
			setIsOpen(true);
			if (btAdapt != null) {
				if (btAdapt.getState() == BluetoothAdapter.STATE_ON) {
					return;
				}
				// 如果现在蓝牙的状态是正在关闭，开启任务
				else if (btAdapt.getState() == BluetoothAdapter.STATE_TURNING_OFF) {
					startOperateBTTimer();
					return;
				}
				btAdapt.enable();
			}
		} catch (Exception e) {

		}
	}

	/**
	 * 关闭蓝牙
	 */
	public void closeBluetooth() {
		try {
			// 设置蓝牙应该存在的状态
			setIsOpen(false);
			if (btAdapt.getState() == BluetoothAdapter.STATE_OFF) {
				return;
			}
			// 如果现在蓝牙的状态是正在打开，开启任务
			else if (btAdapt.getState() == BluetoothAdapter.STATE_TURNING_ON) {
				startOperateBTTimer();
				return;
			}
			btAdapt.disable();

		} catch (Exception e) {
		}
	}

	public boolean isSerchDevice() {
		return isSearch;
	}

	public void setIsSearch(boolean flag) {
		isSearch = flag;
	}

	private void setIsOpen(boolean flag) {
		isOpen = flag;
	}

	private boolean isOpen() {
		return isOpen;
	}

	/**
	 * 停止搜索设备
	 */
	public void stopSearchDeivce() {
		try {
			if (btAdapt != null) {
				btAdapt.cancelDiscovery();// 关闭搜索
			}
		} catch (Exception e) {
		}
	}

	/**
	 * 获取蓝牙状态
	 */
	public int getState() {
		return btAdapt.getState();
	}

	public void setDevPin(String _address, String pwd) {

		BluetoothDevice btDevice = btAdapt.getRemoteDevice(_address);
		try {
			Log.d("mylog", "NOT BOND_BONDED");
			ClsUtils.setPin(btDevice.getClass(), btDevice, pwd); // 手机和蓝牙采集器配对
			ClsUtils.createBond(btDevice.getClass(), btDevice);
			// remoteDevice = btDevice; // 配对完毕就把这个设备对象传给全局的remoteDevice

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 获取本机蓝牙MAC地址
	 */
	public String getLocalBluetoothAddress() {
		return btAdapt.getAddress();
	}

	/**
	 * 本机可以被搜索
	 */
	public void setDiscoverable() {
		Context content = DataBaseManager.getInstance().getContext();
		Intent discoverableIntent = new Intent(
				BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
		discoverableIntent.putExtra(
				BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
		content.startActivity(discoverableIntent);
	}

	/**
	 * 搜索附近蓝牙设备
	 */
	public void startSearch() {
		try {
			if (btAdapt != null) {

				if (!isSearch) {
					btAdapt.startDiscovery();
				} else {
					EffectManager.getInstance().ttsPlay(
							EffectManager.TTS_TYPE_UPTO, context.getString(R.string.findingBlueTooth), false);
				}
			}
		} catch (Exception e) {
		}
	}

	/**
	 * 获取附近其他蓝牙设备信息列表
	 * 
	 * @return
	 */
	public List<BluetoothDevice> getDeviceList() {
		return listDevices;
	}

	public void clearDeviceInfo() {
		listDevices.clear();
	}

	/**
	 * 搜索到设备后添加到蓝牙设备信息列表
	 */
	public void addDevice(BluetoothDevice nDevice) {

		for (BluetoothDevice oDevice : listDevices) {
			// 如果LIST中存在相同的MAC地址的设备
			if (oDevice.getAddress().equals(nDevice.getAddress())) {
				return;
			}
		}

		listDevices.add(nDevice);
	}

	/**
	 * 配对并连接指定mac地址的设备
	 * 
	 * @param _address
	 *            远程mac地址
	 */
	public void connectRemoteDevice(String _address, String message) {
		UUID uuid = UUID.fromString(SPP_UUID);
		// 通过mac地址获取远程设备
		BluetoothDevice btDev = btAdapt.getRemoteDevice(_address);
		try {
			// 与远程设备配对
			btSocket = btDev.createRfcommSocketToServiceRecord(uuid);
			// 与远程设备建立socket连接
			btSocket.connect();
			// 处理数据传输
		} catch (IOException e) {
			try {
				btSocket.close();
				btSocket = null;
			} catch (IOException closeException) {
			}
			return;
		}

		if (btSocket == null) {
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_UPTO,
					context.getString(R.string.devicePairingFailed), false);
			return;
		}
		sendInfo(message);
	}

	public void sendInfo(String message) {
		if (btSocket != null) {
			OutputStream mmOutStream = null;
			try {
				mmOutStream = btSocket.getOutputStream();
			} catch (IOException e) {
			}
			try {
				mmOutStream.write(message.getBytes("GBK"));
				mmOutStream.flush();
			} catch (IOException e) {
				EffectManager.getInstance().ttsPlay(
						EffectManager.TTS_TYPE_UPTO, context.getString(R.string.blueToothSendError), false);
			}

			try {
				btSocket.close();
				btSocket = null;
			} catch (IOException e) {
			}
		}
	}

	public Set<BluetoothDevice> getBondedDevices() {
		return btAdapt.getBondedDevices();
	}

	public boolean hasPairedDevices() {
		if (getBondedDevices().size() > 0) {
			return true;
		} else {
			return false;
		}
	}
}
